package server

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"mcode/pkg/color"

	"github.com/gin-gonic/gin"
)

type GinServer struct {
	engine *gin.Engine
	server *http.Server
	config *Config
}

type Config struct {
	ReadTimeout           time.Duration
	WriteTimeout          time.Duration
	IdleTimeout           time.Duration
	Env                   string
	ServerHeader          string
	BodyLimit             int64
	DisableStartupMessage bool
	AppName               string
	Addr                  string
}

// Option 定义配置选项的函数类型
type Option func(*Config)

// 默认配置
func defaultConfig() *Config {
	return &Config{
		ReadTimeout:  time.Second * 30,
		WriteTimeout: time.Second * 30,
		IdleTimeout:  time.Second * 30,
		Env:          "development",
		ServerHeader: "Gin",
		BodyLimit:    4 * 1024 * 1024, // 4MB
	}
}

// WithAddr 服务器地址
func WithAddr(addr string) Option {
	return func(c *Config) {
		c.Addr = addr
	}
}

// WithReadTimeout 配置选项函数
func WithReadTimeout(t time.Duration) Option {
	return func(c *Config) {
		c.ReadTimeout = t
	}
}

func WithWriteTimeout(t time.Duration) Option {
	return func(c *Config) {
		c.WriteTimeout = t
	}
}

func WithIdleTimeout(t time.Duration) Option {
	return func(c *Config) {
		c.IdleTimeout = t
	}
}

func WithEnv(env string) Option {
	return func(c *Config) {
		c.Env = env
	}
}

func WithServerHeader(header string) Option {
	return func(c *Config) {
		c.ServerHeader = header
	}
}

func WithBodyLimit(limit int64) Option {
	return func(c *Config) {
		c.BodyLimit = limit
	}
}

func WithDisableStartupMessage(env string) Option {
	return func(c *Config) {
		if env == "development" {
			c.DisableStartupMessage = false
		} else {
			c.DisableStartupMessage = true
		}
	}
}

func WithAppName(name string) Option {
	return func(c *Config) {
		c.AppName = name
	}
}

// NewGinServer 创建一个新的 Gin 服务器实例
func NewGinServer(opts ...Option) *GinServer {
	// 使用默认配置
	config := defaultConfig()

	// 应用所有选项
	for _, opt := range opts {
		opt(config)
	}

	// 根据环境设置 Gin 模式
	if config.Env == "production" {
		gin.SetMode(gin.ReleaseMode)
	} else if config.Env == "test" {
		gin.SetMode(gin.TestMode)
	} else {
		gin.SetMode(gin.DebugMode)
	}

	// 创建 Gin 实例
	engine := gin.New()

	// 创建 HTTP 服务器
	server := &http.Server{
		Addr:         config.Addr,
		Handler:      engine,
		ReadTimeout:  config.ReadTimeout,
		WriteTimeout: config.WriteTimeout,
		IdleTimeout:  config.IdleTimeout,
	}

	return &GinServer{
		engine: engine,
		server: server,
		config: config,
	}
}

func (s *GinServer) Engine() *gin.Engine {
	return s.engine
}

func (s *GinServer) Server() *http.Server {
	return s.server
}

// printRoutes 打印所有路由信息（开发模式）
func (s *GinServer) printRoutes() {
	if s.config.Env != "development" {
		return
	}

	fmt.Printf("\n%s\n", color.Colorize("[Gin-debug]", color.Green))
	fmt.Printf("%s %s\n\n",
		color.Colorize("[Gin-debug]", color.Green),
		color.Colorize("Server listening on "+s.config.Addr, color.Yellow),
	)
}

func (s *GinServer) Start() error {
	// 如果是开发环境，打印路由信息
	s.printRoutes()

	return s.server.ListenAndServe()
}

func (s *GinServer) Shutdown(ctx context.Context) error {
	return s.server.Shutdown(ctx)
}
